package com.hzlj.position.config.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.dto.DeleteCommonDTO;
import com.fz.common.base.dto.PageParamDTO;
import com.fz.common.base.dto.QueryPageResultDTO;
import com.fz.common.base.exception.PubException;
import com.fz.common.dict.annotation.DictConvert;
import com.hzlj.position.config.common.dto.operatorActivation.*;
import com.hzlj.position.config.common.dto.operatorActivationLogs.OperatorActivationLogsAddDTO;
import com.hzlj.position.config.common.enums.OperatorActivationStatus;
import com.hzlj.position.config.common.model.OperatorActivation;
import com.hzlj.position.config.converter.OperatorActivationConverter;
import com.hzlj.position.config.dao.OperatorActivationDao;
import com.hzlj.position.config.rest.operator.OperatorLocateRest;
import com.hzlj.position.config.service.OperatorActivationLogsService;
import com.hzlj.position.config.service.OperatorActivationService;
import com.hzlj.position.config.service.OperatorConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.hzlj.position.config.config.IdConfig.POSITION_ID_GEN;

/**
 * 定位-运营商开通(OperatorActivation)表服务接口
 *
 * @author lifh
 * @date 2023-08-10 17:28:24
 */
@Slf4j
@Service
public class OperatorActivationServiceImpl implements OperatorActivationService {
    @Resource
    private OperatorActivationDao operatorActivationDao;
    @Resource
    private OperatorConfigService operatorConfigService;
    @Resource
    private OperatorActivationLogsService operatorActivationLogsService;

    /**
     * 通过id查询单条数据
     *
     * @param id id
     * @return 实例对象
     */
    @Override
    public OperatorActivationQueryResultDTO getOperatorActivationById(String id) {
        OperatorActivation operatorActivation = this.operatorActivationDao.getById(id);
        if (Objects.isNull(operatorActivation)) {
            throw new PubException("没有记录，不能操作!");
        }
        return OperatorActivationConverter.from(operatorActivation);
    }

    @Override
    public OperatorActivationQueryResultDTO getOperatorActivationBySjh(String deviceCode) {
        return this.operatorActivationDao.getOperatorActivationBySjh(deviceCode);
    }

    /**
     * 新增数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOperatorActivation(OperatorActivationAddDTO dto) {
        //是否需要判断有重复情况
        boolean existsBySjh = this.operatorActivationDao.existsBySjh(dto.getSjh());
        if (existsBySjh) {
            throw new PubException("该手机号已存在，请勿重复新增");
        }
        OperatorActivation operatorActivation = OperatorActivationConverter.from(dto);
        operatorActivation.setId(POSITION_ID_GEN.nextIdStr());
        operatorActivation.setActivation(OperatorActivationStatus.INIT.getCode());
        this.operatorActivationDao.save(operatorActivation);
        if (OperatorActivationStatus.isActivation(dto.getActivation())) {
            OperatorActivationDTO activation = BeanUtil.copyProperties(operatorActivation, OperatorActivationDTO.class);
            activation.setActivation(dto.getActivation());
            this.activation(activation);
        }
        log.info("【新增数据成功】:operatorActivation={}", operatorActivation);
    }

    /**
     * 删除数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOperatorActivation(DeleteCommonDTO<String> dto) {
        List<OperatorActivation> activations = this.operatorActivationDao.listByIds(dto.toIds());
        if (!activations.stream().allMatch(e -> OperatorActivationStatus.isInit(e.getActivation()))) {
            throw new PubException("只能删除未开通的记录,请核实！");
        }
        boolean result = this.operatorActivationDao.deleteOperatorActivation(dto);
        if (result) {
            log.info("【删除数据成功】:OperatorActivation={}", dto);
        }
        return result;
    }

    /**
     * 修改数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activation(OperatorActivationDTO dto) {
        //校验
        OperatorActivationQueryResultDTO exists = this.checkActivation(dto);
        boolean activation = OperatorActivationStatus.isActivation(dto.getActivation());
        OperatorActivation update = OperatorActivationConverter.from(dto);
        update.setExt(ObjectUtil.defaultIfNull(exists.getExt(), new OperatorActivationExtDTO()));
        update.setActivationSeconds(exists.getActivationSeconds());
        if (activation) {
            update.setActivationTime(new Date());
        } else {
            update.setDeactivateTime(new Date());
        }
        //匹配运营商
        OperatorConfigService.OperatorTaskConfig operatorTaskConfig = operatorConfigService.taskConfig(dto.getJgCode(), dto.getChannel());
        if (operatorTaskConfig == null) {
            throw new PubException("不存在对应的运营商配置，请联系平台！");
        }
        update.setOperatorConfigId(operatorTaskConfig.getConfig().getId());
        //请求运营商
        OperatorLocateRest operatorLocateRest = operatorTaskConfig.getOperatorLocateRest();
        if (activation) {
            operatorLocateRest.enablePosition(operatorTaskConfig.getConfig(), update.getExt(), dto.getJgCode(), dto.getSjh());
        } else {
            operatorLocateRest.disablePosition(operatorTaskConfig.getConfig(), update.getExt(), dto.getJgCode(), dto.getSjh());
        }
        //修改记录
        boolean success = this.operatorActivationDao.updateOperatorActivation(update);
        //更新日志
        OperatorActivationLogsAddDTO activationLogs = BeanUtil.copyProperties(exists, OperatorActivationLogsAddDTO.class);
        activationLogs.setOperatorActivationId(update.getId());
        activationLogs.setCreatorName(dto.getUpdaterName());
        activationLogs.setCreatorUid(dto.getUpdaterUid());
        operatorActivationLogsService.saveOperatorActivationLogs(activationLogs);
        log.info("【更新数据成功】:operatorActivation={}", success);
        return success;
    }

    private OperatorActivationQueryResultDTO checkActivation(OperatorActivationDTO dto) {
        OperatorActivationQueryResultDTO exists = this.getOperatorActivationById(dto.getId());
        boolean activation = OperatorActivationStatus.isActivation(dto.getActivation());
        //开通
        if (activation) {
            //不能开通
            if (!OperatorActivationStatus.canActivation(exists.getActivation())) {
                throw new PubException("请确认是否重复开通!");
            }
            return exists;
        }
        if (!OperatorActivationStatus.canDeactivate(exists.getActivation())) {
            throw new PubException("请确认是开通状态!");
        }
        return exists;
    }

    /**
     * 查询列表：不分页
     *
     * @param dto 查询条件
     * @return 对象列表
     */
    @Override
    @DictConvert
    public List<OperatorActivationQueryResultDTO> listOperatorActivation(OperatorActivationQueryParamDTO dto) {
        return this.operatorActivationDao.listOperatorActivation(dto);
    }

    /**
     * 查询列表：分页
     *
     * @param dto  查询条件
     * @param page 分页信息
     * @return 对象列表
     */
    @Override
    @DictConvert
    public QueryPageResultDTO<OperatorActivationQueryResultDTO> pageOperatorActivation(OperatorActivationQueryParamDTO dto, PageParamDTO page) {
        return this.operatorActivationDao.pageOperatorActivation(dto, page);
    }
}
